package view.audit
{
	import business.UserDelegate;
	
	import com.adobe.crypto.MD5;
	
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.CheckBox;
	import mx.controls.ComboBox;
	import mx.controls.DataGrid;
	import mx.controls.DateField;
	import mx.controls.Label;
	import mx.controls.LinkButton;
	import mx.controls.RadioButton;
	import mx.controls.RadioButtonGroup;
	import mx.controls.Text;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.events.CloseEvent;
	import mx.rpc.events.FaultEvent;
	
	import util.LogUtil;

	[Bindable]
	public class UserClass extends VBox
	{
		public var m_items:ArrayCollection;
		public var page:int;
		public var pagecnt:int;
		public var pageVolume:int;
		public var pageIndices:Array;
		public var cmEditorType:ComboBox;
		private var selectedIndex:int;
//		public var loaderLock:Boolean;
		public var index:int;
		public var delegateUser:UserDelegate;
		private var type:String; //产品类型
		private var bInSearch:Boolean; //是否在搜索
		private var searchPattern:String; //搜索关键字
		private var searchType:String; //在哪个字段搜索
		private var range:String; //列表范围：审核，未审核，全部

		//界面元件
		public var item_bid:TextInput;
		public var item_sid:TextInput;
		public var item_nickname:TextInput;
		public var item_babynick:TextInput;
		public var item_email:TextInput;
		public var item_secques:TextInput;
		public var item_gender:TextInput;
		public var item_exp:TextInput;
		public var item_level:TextInput;
		public var item_flower:TextInput;
		public var item_money:TextInput;
		public var item_bookCount:TextInput;
		public var item_cardCount:TextInput;
		public var item_createTime:TextInput;
		public var item_lasttime:TextInput;
		public var item_lastip:TextInput;
		public var item_newPass:TextInput;
		public var item_chkStudio:CheckBox;
		public var item_chkBlack:CheckBox;
		public var item_chkResetPass:CheckBox;
		public var item_chkSendMail:CheckBox;
		public var item_chkVip:CheckBox;
		public var item_chkSuper:CheckBox;
		public var item_newPassBox:HBox;
		public var expireField:DateField;
		public var myGrid:DataGrid;

		//newuser
		public var item_newuser_bid:TextInput;
		public var item_newuser_password:TextInput;
		public var item_newuser_email:TextInput;
		private var logId:String = '-1';

		//用户奖（罚）金
		public var labCurrentUserMoney:Label;
		public var radioGroup:RadioButtonGroup;
		public var money:TextInput;
		public var rbPlus:RadioButton;
		public var rbSubtract:RadioButton;
		public var btnUserMoney:Button;
		public var userMoneyType:String = "plus";
		public var txSubmitResult:Text;
		public var taReason:TextArea;

		public function UserClass()
		{
			this.delegateUser = new UserDelegate(this);
			this.range = "all";
			this.page = 0;
			this.index = 0;
			//getPage(this.page);
			this.bInSearch = false;
			this.selectedIndex = -1;
		}

		public function getPage(page:int = 0):void
		{
			if (this.bInSearch)
				this.delegateUser.getUsersBySearch(this.searchPattern, this.searchType, page);
			else
				this.delegateUser.getUsersByAudit(page, this.range);

			//if (item_box)
				//item_box.enabled = false;
		}

		private function updateItem(ids:Array, update:Object):void
		{
			var obj:Object = new Object();
			obj.ids = ids;
			obj.update = update;
			LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.USER, LogUtil.UPDATE, obj, '', '', true);
			this.delegateUser.updateUsers(ids, update);
		}

/*
		private function goUpdateItem(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goUpdateItem);
			this.logId = event.logId;
			this.delegateUser.updateUsers(event.record.ids,event.record.update);
		}
*/

		private function removeItem(page:int, ids:Array):void
		{
		}

		private function refreshPage(result:Object):void
		{
			result = result.result;
			this.page = result.page > 0 ? result.page : 0;
			this.pagecnt = result.pagecnt > 1 ? result.pagecnt : 1;
			this.makePageIndices();
			this.itemsPrepare(result.users);
		}

		public function itemsPrepare(items:Array, method:String = "get"):void
		{
			//预处理结果集
			for each (var myitem:Object in items)
			{
				//初始化vip过期时间
				if (myitem.vipExpireTime != 0)
				{
					var formateVipExpireTime:Date = new Date();
					formateVipExpireTime.setTime(Number(myitem.vipExpireTime) * 1000);
					myitem.vipExpireTime = formateVipExpireTime;
				}
				else
				{
					myitem.vipExpireTime = new Date();
				}
			}

			if (method == "get")
			{
				this.m_items = new ArrayCollection(items);
			}
			else if (method == "update")
			{
				var newItems:ArrayCollection = new ArrayCollection(items);
				for each (var item1:Object in newItems)
				{
					for (var i:int = 0; i < this.m_items.length; ++i)
					{
						if (this.m_items[i].bid == item1.bid)
						{
							this.m_items[i] = item1;
							break;
						}
					}
				}
			}
			else if (method == "delete")
			{
				for each (var bid:int in items)
				{
					for (var j:int = 0; j < this.m_items.length; ++j)
					{
						if (this.m_items[j].bid == bid)
						{
							this.m_items.removeItemAt(j);
							break;
						}
					}
				}
			}

			for each (var item:Object in this.m_items)
			{
				item.oldid = item.bid;
//				item.superUserChk = false;
				if (item.status < 0)//小于0=黑名单，等于0=普通，等于1=红人
				{
					item.statusCheck = true;
					item.superUserChk = false;
					item_chkBlack.selected = true;
				}
				else
				{
					item.statusCheck = false;
					if (item.status == 1)
						item.superUserChk = true;
					else
						item.superUserChk = false;
				}

				if(item.status == 1)
					item_chkSuper.selected = true;
				else
					item_chkSuper.selected = false;

				if(item.type == 0)
					item_chkStudio.selected = false;
				else
					item_chkStudio.selected = true;

				if (item.vip == '1')
					item.vipCheck = true;
				else
					item.vipCheck = false;

				item.allCount = int(item.bookCount) + int(item.cardCount);
			}
		}
		public var superUserChk:Boolean;

		public function updatePrepare():Object
		{
			if (myGrid.selectedItem == null)
				return null;

			var update:Object = new Object();

			/*
			   if(myGrid.selectedItem.bid != item_bid.text)
			   {
			   update.bid = item_bid.text;

			   //如果更改了ID，需要同步修改
			   //myGrid.selectedItem.oldid = item_bid.text;
			   myGrid.selectedItem.bid = item_bid.text;
			   }
			 */

			if (myGrid.selectedItem.nickname != item_nickname.text)
				update.nickname = item_nickname.text;

			//if(myGrid.selectedItem.babynick != item_babynick.text)
			//	update.babynick = item_babynick.text;

			if (myGrid.selectedItem.sid != item_sid.text)
				update.sid = item_sid.text;

			if (myGrid.selectedItem.email != item_email.text)
				update.email = item_email.text;

			if (myGrid.selectedItem.secques != item_secques.text)
				update.secques = item_secques.text;

			if (myGrid.selectedItem.gender != item_gender.text)
				update.gender = item_gender.text;

			if (myGrid.selectedItem.exp != item_exp.text)
				update.exp = item_exp.text;

			if (myGrid.selectedItem.level != item_level.text)
				update.level = item_level.text;

			if (myGrid.selectedItem.flower != item_flower.text)
				update.flower = item_flower.text;

			if (myGrid.selectedItem.money != item_money.text)
				update.money = item_money.text;

			if ((myGrid.selectedItem.statusCheck!=item_chkBlack.selected) || (myGrid.selectedItem.superUserChk!=item_chkSuper.selected))//只有更改了是否黑名单的选项才添加status属性
			{
				if ( item_chkBlack.selected )
					update.status = 111; //数据库存 -1
				else if( item_chkSuper.selected )
					update.status = 1;
				else
					update.status = 0;
			}

			if (myGrid.selectedItem.vipCheck != item_chkVip.selected)
				if (item_chkVip.selected)
					update.vip = 1;
				else
					update.vip = 0;

			if (myGrid.selectedItem.vipExpireTime.time != expireField.selectedDate.time)
				update.vipExpireTime = (expireField.selectedDate as Date).getTime() / 1000;

			if (item_chkResetPass.selected && item_newPass.text.length > 0)
				update.password = MD5.hash(item_newPass.text);

			if (myGrid.selectedItem.type != item_chkStudio.selected)
				if (item_chkStudio.selected)
					update.type = 1;
				else
					update.type = 0;
			//TODO: 发信给用户
			return update;
		}

		public function onSubmit():void
		{
			if (myGrid.selectedItem == null)
			{
				Alert.show("请先选择要管理的用户");
				return;
			}

			//处理update
			var update:Object = this.updatePrepare();
			if (update == null)
				return;

			var ids:Array = [];
			ids.push(myGrid.selectedItem.oldid);
			updateItem(ids, update);

//			if (item_chkSuper.selected != this.myGrid.selectedItem.superUserChk)//红人状态更改了
//			{
//				var stat:String = item_chkSuper.selected ? ApplySuperUserAuditClass.STATUS_PASSED : '0';//ApplySuperUserAuditClass.STATUS_REJECT;//这里发送拒绝红人信息BUG
//				Application.application.applySuperUserAdit.setSuperUser(myGrid.selectedItem.bid, stat, '');
//			}
		}

		public function onDataGridItemClick():void
		{
			if (myGrid.selectedItem == null)
				return;
			this.txSubmitResult.text = '';
/*
			if ( myGrid.selectedIndex == this.selectedIndex )
				return;

			this.selectedIndex = myGrid.selectedIndex;
*/
			 //item_box.enabled = true;
			 //Application.application.parameters.info = myGrid.selectedItem.flashVars;
			 //item_player.load();	
		}

		public function getUsersByAuditResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}

		public function getUsersBySearchResult(result:Object, token:Object = null):void
		{
			this.refreshPage(result);
		}

		public function removeUsersResult(result:Object, token:Object = null):void
		{
			//Alert.show("删除成功");
			//refreshPage(result);

			result = result.result;
			this.itemsPrepare(result.ids, "delete");
		}

		public function updateUsersResult(result:Object, token:Object = null):void
		{
			result = result.result;
			this.itemsPrepare(result.users, "update");
		}

		public function onRangeClick(method:String):void
		{
			this.range = method;
			this.getPage();
		}

		public function onSearch(type:int, pattern:String):void
		{
			if (pattern.length <= 0)
				return;

			this.searchPattern = pattern;

			if (type == 0)
				this.searchType = 'bid';
			else if (type == 1)
				this.searchType = 'email';
			else if (type == 2)
				this.searchType = 'nickname';
			else if (type == 3)
				this.searchType = 'game';

			this.bInSearch = true;
			getPage(page);
		}

		public function goto(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.page;
			getPage(page);
		}

		private function makePageIndices():void
		{
			var a:Array = new Array();
			a.push({page: 0, desc: '首页'});
			a.push({page: page - 1, desc: '前一页'});
			a.push({page: page + 1, desc: '后一页'});
			a.push({page: pagecnt - 1, desc: '尾页'});
			this.pageIndices = a;
		}

		public function onResetPass():void
		{
			if (item_chkResetPass.selected)
				item_newPassBox.enabled = true;
			else
				item_newPassBox.enabled = false;
		}

		public function onRefreshClick():void
		{
			this.bInSearch = false;
			getPage();
		}

		public function onLabelSpaceClick():void
		{
			var u:URLRequest = new URLRequest(myGrid.selectedItem.url);
			navigateToURL(u, "_blank");
		}

		public function fault(error:FaultEvent, token:Object = null):void
		{
			Alert.show(error.fault.faultString, 'error');
		}

		public function onBtnClearUserClick():void
		{
			//处理删除
			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.buttonWidth = 50;
			Alert.buttonHeight = 20;
			Alert.show('“清除”操作会重置用户头像，确定吗？', '提示', Alert.YES | Alert.NO, null, onClearUserConfirmed, null, Alert.NO);
			return;
		}

		private function onClearUserConfirmed(event:CloseEvent):void
		{
			if (event.detail == Alert.YES)
			{
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.USER, LogUtil.UPDATE, {bid: myGrid.selectedItem.bid}, '', '', true);
				this.delegateUser.clearPic(myGrid.selectedItem.bid);
			}
		}

		public function clearPicUserResult(result:Object, token:Object = null):void
		{
		}

		public function onBtnNewuserCommit():void
		{
			//处理删除
			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.buttonWidth = 50;
			Alert.buttonHeight = 20;
			Alert.show('确定要发放此宝宝号？', '提示', Alert.YES | Alert.NO, null, onNewuserConfirmed, null, Alert.NO);
			return;
		}

		private function onNewuserConfirmed(event:CloseEvent):void
		{
			if (event.detail == Alert.YES)
			{
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.USER, LogUtil.ADD, {bid: item_newuser_bid.text, password: item_newuser_password.text, email: item_newuser_email.text}, '', '', true);
				this.delegateUser.registerUserSys(item_newuser_bid.text, item_newuser_password.text, item_newuser_email.text);
			}
		}

		public function registerUserSysResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if (result.code == 0)
			{
				item_newuser_bid.text = "";
				item_newuser_password.text = "";
				item_newuser_email.text = "";
				Alert.show("发放成功！");
			}
			else
			{
				Alert.show(result.msg);
			}
		}

		public function addExpire(addMonth:int):void
		{
			if (addMonth > 0)
			{
				var currentDate:Date = expireField.selectedDate;
				currentDate.setMonth(currentDate.getMonth() + addMonth);
				expireField.selectedDate = currentDate;
			}
			else
			{
				expireField.selectedDate = new Date(2009, 0, 1);
			}
		}

		/**查看用户爱拍币*/
		public function onBtnGetMoneyClick(bid:String):void
		{
			this.delegateUser.getMoney(bid);
		}

		public function getMoneyResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if (result.code == 0)
				this.labCurrentUserMoney.text = result.data == undefined ? '0' : result.data;
		}

		public function getMoneyFault(error:FaultEvent, token:Object = null):void
		{
			Alert.show(error.fault.faultString, '查看用户爱拍币失败');
			initBtnUserMoney();
		}

		/**奖罚用户爱拍币*/
		public function onBtnUserMoneyClick(nickname:String):void
		{
			Alert.yesLabel = "确定";
			Alert.noLabel = "取消";
			Alert.show("对呢称为\"" + nickname + "\"的用户" + this.radioGroup.selectedValue + money.text + "爱拍币？", "用户赏（罚）金", Alert.YES | Alert.NO, null, closeUserMoneyAlert, null, Alert.YES);
		}
		private var aipaiCurrency:String;

		private function closeUserMoneyAlert(e:CloseEvent):void
		{
			if (e.detail == Alert.YES)
			{
				if (this.userMoneyType == 'plus')
					this.aipaiCurrency = money.text;
				if (this.userMoneyType == 'subtract')
					this.aipaiCurrency = '-' + money.text;

				this.delegateUser.addMoney(this.myGrid.selectedItem.bid, this.aipaiCurrency, 101, taReason.text);
			}
			else if (e.detail == Alert.NO)
			{
				initBtnUserMoney();
			}
		}

		public function addMoneyResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if (result.code == 0)
			{
				onBtnGetMoneyClick(this.myGrid.selectedItem.bid);
				this.txSubmitResult.text = this.userMoneyType == 'plus' ? '奖赏成功！' : '扣除成功！';
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.USER, LogUtil.UPDATE, {bid: this.myGrid.selectedItem.bid, AddMoney: this.aipaiCurrency, Reason: taReason.text}, '', 'Aipai Currency Manage', true);
				initBtnUserMoney();
			}
			else
			{
				onBtnGetMoneyClick(this.myGrid.selectedItem.bid);
				this.txSubmitResult.text = this.userMoneyType == 'plus' ? '奖赏失败！' : '扣除失败！';
				initBtnUserMoney();
			}
		}

		public function addMoneyFault(error:FaultEvent, token:Object = null):void
		{
			Alert.show(error.fault.faultString, this.userMoneyType == 'plus' ? '奖赏失败！' : '扣除失败！');
			initBtnUserMoney();
		}

		public function initBtnUserMoney():void
		{
			this.labCurrentUserMoney.text = '0';
			money.text = "0";
			this.userMoneyType = 'plus'; //rbPlus.selected = true;
		}
	}
}